﻿using orangesGame;
using UnityEngine.Advertisements;
using UnityEngine;

public class UnityAdsvertisement : AdsBase, IUnityAdsListener
{
    private AdsEventListen _bannerEvent;
    private AdsEventListen _interEvent;
    private AdsEventListen _videoEvent;

    private string _interID;
    private string _videoID;

    public override void Init(AdsArgs args)
    {
        base.Init(args);
        _bannerEvent = args.BannerEvent;
        _interEvent = args.InterstitialEvent;
        _videoEvent = args.VideoEvent;
        _interID = args.InterstitialIDs[0];
        _videoID = args.VideoIDs[0];
        Advertisement.Initialize(args.Appkey, false);
        Advertisement.AddListener(this);
    }



    public override void LoadInterstitial(string id)
    {
        base.LoadInterstitial(id);
        Advertisement.Load(id);
    }

    public override void LoadVideo(string id)
    {
        base.LoadVideo(id);
        Advertisement.Load(id);
    }

    public void OnUnityAdsDidError(string message)
    {
        _interEvent.OnError(_interID, message);
        _videoEvent.OnError(_videoID, message);
    }

    public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
    {
        if (showResult == ShowResult.Finished)
        {
            if (placementId == _videoID)
            {
                _videoEvent.OnReward(placementId);
                _videoEvent.OnClose(placementId);
            }
            else if (placementId == _interID)
            {
                _interEvent.OnClose(placementId);
            }
        };
    }

    public void OnUnityAdsDidStart(string placementId)
    {
        //if (placementId == _interID)
        //{
        //    _interEvent.OnStart(placementId);
        //}
        //else if (placementId == _videoID)
        //{
        //    _videoEvent.OnStart(placementId);
        //}
    }

    public void OnUnityAdsReady(string placementId)
    {
        if (placementId == _interID)
        {
            _interEvent.OnLoad(placementId);
        }
        else if (placementId == _videoID)
        {
            _videoEvent.OnLoad(placementId);
        }
    }

    public override void ShowInterstitial(string id)
    {
        base.ShowInterstitial(id);
        if (Advertisement.IsReady(id))
        {
            Advertisement.Show(id);
        }
    }

    public override void ShowVideo(string id)
    {
        base.ShowVideo(id);
        if (Advertisement.IsReady(id))
        {
            Advertisement.Show(id);
        }
    }

}
